import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:get/get.dart';
import 'package:sweetim/model/friends.dart';
import 'package:sweetim/model/simple_message.dart';

import '../controller/chat_controller.dart';

class ChatDetails extends StatelessWidget {
  final Friends friends;

  const ChatDetails({required this.friends, Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    ChatController chatController = Get.put(ChatController(friends.id!));
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.keyboard_arrow_left),
          onPressed: () {
            if (chatController.msgList.isNotEmpty) {
              Get.back(result: chatController.msgList.first.content);
            } else {
              Get.back();
            }
          },
        ),
        title: Row(
          children: [
            Text(friends.name ?? ""),
          ],
        ),
      ),
      body: SafeArea(
        top: true,
        bottom: true,
        child: Column(
          children: [
            Expanded(
              flex: 9,
              child: Obx(() =>
                  chatController.msgList.isEmpty && chatController.loading.value
                      ? const Center(child: CircularProgressIndicator())
                      : ListView.builder(
                          reverse: true,
                          controller: chatController.scrollController,
                          padding: const EdgeInsets.all(8.0),
                          key: const PageStorageKey("chat_msg_list"),
                          itemCount: chatController.msgList.length,
                          itemBuilder: (ctx, index) {
                            if(chatController.loadMoreFlag.value && index == chatController.msgList.length-1) {
                              Get.log("加载更多，显示loading index: $index, len: ${chatController.msgList.length-1}");
                              return const Padding(
                                padding: EdgeInsets.all(8.0),
                                child: Center(
                                  child: SizedBox(
                                      height: 15,
                                      width: 15,
                                      child: CircularProgressIndicator(
                                        strokeWidth: 3,
                                      )
                                  ),
                                ),
                              );
                            }
                            return Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: MsgItem(chatController.name(), friends,
                                  chatController.msgList[index]),
                            );
                          },
                        )),
            ),
            const Divider(color: Colors.grey),
            Expanded(
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 2.0),
                child: Row(
                  children: [
                    IconButton(
                        onPressed: () {},
                        icon: const FaIcon(FontAwesomeIcons.image)),
                    IconButton(
                        onPressed: () {},
                        icon: const FaIcon(FontAwesomeIcons.laughWink)),
                    Expanded(
                      child: TextField(
                        controller: chatController.textController,
                        minLines: 1,
                        maxLines: 20,
                        style: const TextStyle(fontSize: 16),
                        decoration: const InputDecoration(
                          contentPadding: EdgeInsets.all(1),
                          border: OutlineInputBorder(),
                        ),
                      ),
                    ),
                    IconButton(
                      onPressed: () =>
                          chatController.sendMsg(friends.id.toString()),
                      icon: const FaIcon(FontAwesomeIcons.telegramPlane),
                    ),
                  ],
                ),
              ),
              flex: 1,
            ),
          ],
        ),
      ),
    );
  }
}

class MsgItem extends StatelessWidget {
  final Friends friends;
  final String name;
  final SimpleMessage message;

  const MsgItem(this.name, this.friends, this.message, {Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<Widget> list;
    if (message.sid == friends.id) {
      // 朋友发来的消息
      list = [
        CircleAvatar(
          backgroundColor: Colors.indigo[200],
          radius: 18,
          child: Text(
            friends.name?.substring(0, 1) ?? "",
          ),
        ),
        const SizedBox(width: 8),
        Flexible(
          child: Container(
            padding: const EdgeInsets.all(8.0),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4.0),
                color: Colors.teal[100]),
            child: Text(
              message.content ?? "",
              maxLines: double.maxFinite.toInt(),
              softWrap: true,
            ),
          ),
        ),
        const SizedBox(width: 30),
      ];
    } else {
      list = [
        const SizedBox(width: 30),
        Flexible(
          child: Container(
            padding: const EdgeInsets.all(8.0),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4.0),
                color: Colors.teal[100]),
            child: Text(
              message.content ?? "",
              maxLines: double.maxFinite.toInt(),
              softWrap: true,
            ),
          ),
        ),
        const SizedBox(width: 8),
        CircleAvatar(
          backgroundColor: Colors.indigo[200],
          radius: 18,
          child: Text(
            name.substring(0, 1),
          ),
        ),
      ];
    }
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: message.sid == friends.id
          ? MainAxisAlignment.start
          : MainAxisAlignment.end,
      children: list,
    );
  }
}
